import jwt from 'jsonwebtoken';
import { Response, Request, NextFunction } from 'express';
import config from '@/config/config.default';

function authVertify(req: Request, res: Response, next: NextFunction) {
  // 从请求头中获取 token
  const token = req.headers['authorization'];
  if (!token) {
    // 没有 token，返回 401 Unauthorized
    return res.status(401).send({ code: 401, message: '未登录', data: null });
  }
  try {
    // 验证 token 是否合法
    const decoded = jwt.verify(token, config.tokenSecrets);
    res.locals.user = decoded;
    next();
  } catch (err) {
    // token 不合法，返回 403 Forbidden
    return res
      .status(403)
      .send({ code: 403, message: '登录已过期，请重新登录', data: null });
  }
}

export default authVertify;
